/*
 *  Copyright 2004 Blandware (http://www.blandware.com)
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.blandware.atleap.webapp.action.core.contentField;

import com.blandware.atleap.common.Constants;
import com.blandware.atleap.model.core.ActionPage;
import com.blandware.atleap.model.core.ContentField;
import com.blandware.atleap.model.core.ContentPage;
import com.blandware.atleap.model.core.Layout;
import com.blandware.atleap.model.core.Localizable;
import com.blandware.atleap.model.core.Page;
import com.blandware.atleap.search.SearchManager;
import com.blandware.atleap.service.core.ContentFieldManager;
import com.blandware.atleap.service.core.PageManager;
import com.blandware.atleap.webapp.action.core.BaseAction;
import com.blandware.atleap.webapp.form.core.ContentFieldForm;
import com.blandware.atleap.webapp.util.core.CacheUtil;
import com.blandware.atleap.webapp.util.core.WebappConstants;
import com.blandware.atleap.webapp.util.core.WebappUtil;
import org.apache.commons.validator.GenericValidator;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * <p>Deletes content field
 * </p>
 * <p><a href="DeleteContentFieldAction.java.html"><i>View Source</i></a></p>
 * <p/>
 *
 * @author Sergey Zubtsovskiy <a href="mailto:sergey.zubtsovskiy@blandware.com">&lt;sergey.zubtsovskiy@blandware.com&gt;</a>
 * @author Andrey Grebnev <a href="mailto:andrey.grebnev@blandware.com">&lt;andrey.grebnev@blandware.com&gt;</a>
 * @version $Revision: 1.34 $ $Date: 2008/04/29 17:48:05 $
 * @struts.action path="/core/contentField/delete"
 * name="contentFieldForm"
 * scope="request"
 * validate="false"
 * roles="core-contentField-delete, core-contentField-deleteOverriden, core-contentField-deleteIndexed"
 * @struts.action-forward name="listContentFields"
 * path="/core/contentField/list.do"
 * redirect="false"
 */
public final class DeleteContentFieldAction extends BaseAction {
	/**
	 * @param mapping  The ActionMapping used to select this instance
	 * @param form     The optional ActionForm bean for this request (if any)
	 * @param request  The HTTP request we are proceeding
	 * @param response The HTTP response we are creating
	 * @return an ActionForward instance describing where and how
	 *         control should be forwarded, or null if response
	 *         has already been completed
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form,
	                             HttpServletRequest request, HttpServletResponse response) throws Exception {

        HttpSession session = request.getSession();
        ContentFieldForm contentFieldForm = (ContentFieldForm) form;

        // Check whether it's normal deletion (from list of content fields) or
		// it was invoked from context menu
		String redirUrl = request.getParameter("redirectUrl");
        if ( !GenericValidator.isBlankOrNull(redirUrl) ) {
			// It was invoked from context menu
			session.setAttribute(WebappConstants.REDIRECT_URL_KEY, redirUrl);
		}

        String requestUrl = (String) session.getAttribute(WebappConstants.REDIRECT_URL_KEY);

        Long ownerId = null;
		if ( !GenericValidator.isBlankOrNull(contentFieldForm.getOwnerId()) ) {
			ownerId = Long.valueOf(contentFieldForm.getOwnerId());
		} else {
			if ( log.isWarnEnabled() ) {
				log.warn("Missing owner ID. Returning to index...");
			}
            if ( !GenericValidator.isBlankOrNull(requestUrl) ) {
                session.removeAttribute(WebappConstants.REDIRECT_URL_KEY);
                return new ActionForward(requestUrl, true);
            }
            return mapping.findForward("admin");
		}

        session.setAttribute(WebappConstants.OWNER_ID_KEY, ownerId);

		Long contentFieldId = null;
		if ( !GenericValidator.isBlankOrNull(contentFieldForm.getId()) ) {
			contentFieldId = Long.valueOf(contentFieldForm.getId());
		} else {
			if ( log.isWarnEnabled() ) {
				log.warn("Missing content field ID. Returning to list...");
			}
            if ( !GenericValidator.isBlankOrNull(requestUrl) ) {
                session.removeAttribute(WebappConstants.REDIRECT_URL_KEY);
                return new ActionForward(requestUrl, true);
            }
            return mapping.findForward("listContentFields");
		}

		ContentFieldManager contentFieldManager = (ContentFieldManager) getBean(Constants.CONTENT_FIELD_MANAGER_BEAN);
		ContentField contentField = contentFieldManager.retrieveContentField(contentFieldId);

		if ( contentField == null ) {
			// content field not found. it might be deleted by someone else
			ActionMessages errors = new ActionMessages();
			errors.add("contentFieldNotFound", new ActionMessage("core.contentField.errors.notFound"));
			saveErrors(request, errors);
            if ( !GenericValidator.isBlankOrNull(requestUrl) ) {
                session.removeAttribute(WebappConstants.REDIRECT_URL_KEY);
                return new ActionForward(requestUrl, true);
            }
            return mapping.findForward("listContentFields");
		}

		Localizable owner = contentField.getOwner();
		if ( owner instanceof Layout && !request.isUserInRole("core-contentField-delete") ) {

			String fieldIdentifier = contentField.getIdentifier();
			int k = fieldIdentifier.indexOf('[');
			String index = null;
			if ( k != -1 ) {
				index = fieldIdentifier.substring(k + 1, fieldIdentifier.indexOf(']', k));
				fieldIdentifier = fieldIdentifier.substring(0, k);
				contentFieldForm.setIdentifier(fieldIdentifier);
				contentFieldForm.setIndex(index);
			}

            Set identifiers = WebappUtil.getOverridableFieldIdentifiers(owner,  request);
            boolean overridable = identifiers.contains(fieldIdentifier);

			if ( !overridable && (index == null || index.equalsIgnoreCase("0")) ) {
				ActionMessages errors = new ActionMessages();
				errors.add("contentFieldCannotDelete", new ActionMessage("core.contentField.errors.unindexed.cannotDelete"));
				saveErrors(request, errors);
                if ( !GenericValidator.isBlankOrNull(requestUrl) ) {
                    session.removeAttribute(WebappConstants.REDIRECT_URL_KEY);
                    return new ActionForward(requestUrl, true);
                }
                return mapping.findForward("listContentFields");
			}
		}

        // Forbid to delete field from action page if this field is not a
        // "redifinition" and user has no rights to delete fields
        if (owner instanceof ActionPage && !request.isUserInRole("core-contentField-delete")) {
            Set identifiers = WebappUtil.getOverridableFieldIdentifiers(owner, request);
            String identifier = contentField.getIdentifierWithoutIndex();
			boolean canDelete = identifiers != null && !identifiers.isEmpty() && identifiers.contains(identifier);
            if (!canDelete) {
				ActionMessages errors = new ActionMessages();
				errors.add("contentFieldCannotDelete", new ActionMessage("core.contentField.errors.actionPageField.cannotDelete"));
				saveErrors(request, errors);
                if ( !GenericValidator.isBlankOrNull(requestUrl) ) {
                    session.removeAttribute(WebappConstants.REDIRECT_URL_KEY);
                    return new ActionForward(requestUrl, true);
                }
                return mapping.findForward("listContentFields");
            }
        }

		contentFieldManager.deleteContentField(contentFieldId);

		//flush cache
		CacheUtil cacheUtil = CacheUtil.getInstance(request);
		cacheUtil.flushFieldIndices();

		// put into search index
		SearchManager searchManager = SearchManager.getInstance(session.getServletContext());
		if ( owner instanceof Layout ) {
			Layout layout = (Layout) owner;

			//add into search index for every content page of the layout.
			List contentPages = layout.getContentPages();
			for ( int i = 0; i < contentPages.size(); i++ ) {
				ContentPage contentPage = (ContentPage) contentPages.get(i);
				cacheUtil.updateContentPageLastModifiedInCache(contentPage.getUri());
				searchManager.reIndexPage(contentPage, request);
			}
			cacheUtil.flushLayoutFieldValueCache(layout.getDefinition());

		} else if ( owner instanceof Page ) {
			Page page = (Page) owner;
			searchManager.reIndexPage(page, request);
			cacheUtil.flushPageFieldValueCache(page.getUri());
			if ( owner instanceof ContentPage ) {
				cacheUtil.updateContentPageLastModifiedInCache(page.getUri());
			}

            // updating 'update time'
            PageManager pageManager = (PageManager) getBean(Constants.PAGE_MANAGER_BEAN);
            page.setLastUpdatedDatetime(new Date());
            pageManager.updatePage(page);
        }

		session.setAttribute(WebappConstants.OWNER_ID_KEY, ownerId);
        if ( !GenericValidator.isBlankOrNull(requestUrl) ) {
            session.removeAttribute(WebappConstants.REDIRECT_URL_KEY);
            return new ActionForward(requestUrl, true);
        }
        return mapping.findForward("listContentFields");
	}
}